package com.haoze.nurseapp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.model.TaskExecuteBatchEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.BloodMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.dao.TaskExecuteDetailMapper;
import com.haoze.nurseapp.dao.UserMapper;
import com.haoze.nurseapp.dto.task.TaskExecuteBatchDTO;
import com.haoze.nurseapp.model.ReceiveBloodRecordEntity;
import com.haoze.nurseapp.model.TaskExecuteDetailEntity;
import com.haoze.nurseapp.model.UserEntity;
import com.haoze.nurseapp.service.BloodService;
import com.haoze.nurseapp.service.NursePatientOrderService;
import com.haoze.nurseapp.service.feign.PatientOrderService;
import com.haoze.nurseapp.vo.BloodVo;
import com.haoze.nurseapp.vo.patient.InHospitalPatientVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: Chenchao
 * @CreateTime: 2020-04-14 10:37
 */
@Service
public class BloodServiceImpl implements BloodService {

    @Resource
    private BloodMapper bloodMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    TaskExecuteDetailMapper taskExecuteDetailMapper;

    @Resource
    NursePatientOrderService patientOrderService;

    @Resource
    PatientInHospitalMapper patientInHospitalMapper;

    @Override
    public Result getBloodList(String wardId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        PageInfo<BloodVo> pageInfo = new PageInfo<>(bloodMapper.getBloodList(wardId, null));
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result receiveBlood(List<String> reqNums) {
        String id = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        UserEntity currentUser = userMapper.selectByPrimaryKey(id);
        List<ReceiveBloodRecordEntity> recordEntityList = new CopyOnWriteArrayList<>();
        List<TaskExecuteBatchEntity> taskExecuteDetailEntitys = new CopyOnWriteArrayList<>();
        reqNums.stream().distinct().forEach(x ->{
            ReceiveBloodRecordEntity receiveBloodRecordEntity = new ReceiveBloodRecordEntity();
            List<BloodVo> list = bloodMapper.getBloodList(null, x);
            list.stream().forEach(y->{
                receiveBloodRecordEntity.initAdd();
                receiveBloodRecordEntity.setBloodBagCoding(y.getBloodBagCoding());
                receiveBloodRecordEntity.setBloodReceiveId(UUIDUtil.randomString());
                receiveBloodRecordEntity.setInpatNum(y.getInpatNum());
                receiveBloodRecordEntity.setReqNum(x);
                receiveBloodRecordEntity.setTransfusionId(y.getTransfusionId());
                receiveBloodRecordEntity.setWardDeptId(y.getWardDeptId());
                receiveBloodRecordEntity.setReceivePersonId(currentUser.getUserId());
                receiveBloodRecordEntity.setReceivePersonName(currentUser.getUserName());
                receiveBloodRecordEntity.setType(y.getType());
                recordEntityList.add(receiveBloodRecordEntity);
                if(receiveBloodRecordEntity.getType().equals("receive")) taskExecuteDetailEntitys.add(taskExecuteDetailMapper.queryInfoByBarCode(y.getQrCode()));
            });
        });


        // 查询当前节点是否正处在待完成
        List<Map<String,Object>> listMap = new ArrayList<>();
        for (int j = 0; j < taskExecuteDetailEntitys.size(); j++) {
            Map<String,Object> entityMap = new HashMap<>();
            TaskExecuteBatchEntity taskExecuteDetailEntity = taskExecuteDetailEntitys.get(j);
            if(null == taskExecuteDetailEntity) continue;
            taskExecuteDetailEntity.setExecutePersonId(currentUser.getUserId());
            entityMap.put("taskExecuteDetailEntity",taskExecuteDetailEntity);
            entityMap.put("userId",currentUser.getUserId());
            listMap.add(entityMap);
        }
        try {
            bloodMapper.insertReceiveBloodRecordEntity(recordEntityList);
            //创建下一个节点
            patientOrderService.createNextTaskNodeList(listMap,"");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return ResultGenerator.genOkResult("领血完成");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result receiveBloodToDept(String qrCode) {
        String id = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        // 查询当前节点是否正处在待完成
        List<Map<String,Object>> listMap = new ArrayList<>();
        Map<String,Object> entityMap = new HashMap<>();
        TaskExecuteBatchEntity taskExecuteDetailEntity = taskExecuteDetailMapper.queryInfoByBarCode(qrCode);
        if(null == taskExecuteDetailEntity) return ResultGenerator.genOkResult("没找到任务节点");
        taskExecuteDetailEntity.setExecutePersonId(id);
        entityMap.put("taskExecuteDetailEntity",taskExecuteDetailEntity);
        entityMap.put("userId",id);
        listMap.add(entityMap);
        try {
            //创建下一个节点
            patientOrderService.createNextTaskNodeList(listMap,"");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return ResultGenerator.genOkResult("任务节点完成");
    }

    public Result queryBloodList(String startDate,String endDate,String keywords,Integer pageNum,Integer pageSize,String wardId,String nodeType){
        PageHelper.startPage(pageNum, pageSize);
        List<BloodVo> bloodList = new ArrayList<BloodVo>();
        if("ck_xklx".equals(nodeType)){
            //待领取
            bloodList = bloodMapper.queryBloodListByUnclaimed(startDate, endDate, keywords, wardId);
        }else if("ck_thxd".equals(nodeType)){
            //已退还
            bloodList = bloodMapper.queryBloodListByReturn(startDate, endDate, keywords, wardId);
        }else if("ck_srhdlx".equals(nodeType) || "ck_srhdsx".equals(nodeType)){
             //待确认、待执行
            bloodList = bloodMapper.queryBloodListByStatus(startDate, endDate, keywords, wardId,"0",nodeType);
        }else if("ck_jssx".equals(nodeType)){
            //已执行
            bloodList = bloodMapper.queryBloodListByStatus(startDate, endDate, keywords, wardId,"1",nodeType);
        }
        PageInfo<BloodVo> pageInfo = new PageInfo<BloodVo>(bloodList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    /**
     * 获取患者信息
     * @param inpatNum
     * @return
     */
    public Result queryPatientDetailByInpatNum(String inpatNum){
        InHospitalPatientVO inHospitalPatientVO = patientInHospitalMapper.queryPatientCirculationDetailByInpatNum(inpatNum);
        return ResultGenerator.genOkResult(inHospitalPatientVO);
    }

    /**
     * 获取血液信息
     */
    public Result queryBloodInfoByBloodBagCode(String bloodBagCoding){
        return ResultGenerator.genOkResult(bloodMapper.queryBloodInfoByBloodBagCode(bloodBagCoding));
    }

}
